/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tabox.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author rendy
 */
public class Handler extends Thread{
    
    Socket socket;
    Protocol protocol;
    
    public Handler(Socket socket){
        this.socket = socket;
    }
    
    @Override
    public void run(){
        try {
            protocol = new Protocol();
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String inputLine, outputLine;
            
            out.println("CONNECTED");

            while ((inputLine = in.readLine()) != null) {
                protocol.process(inputLine.split(" "));
                outputLine = protocol.getStatus();
                if (outputLine.equals("BYE"))
                    break;                
                out.println(outputLine);
                System.out.println(inputLine);
            }
            in.close();
            out.close();
            socket.close();
            System.out.println("HANDLER STOPPED");
        } catch (SQLException ex) {
            Logger.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
